import axios from 'axios'

import { store } from '@/stores'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isNull } from './index'
import { tansParams } from '@/utils/paramUtils'
import errorCode from '@/utils/errorCode'
import qs from 'qs'

const FROM_TYPE = 'form'

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // 如果type是from,则是表单提交
    if (config.type === FROM_TYPE) {
      config.transformRequest = [function (data) {
        return qs.stringify(data, { allowDots: true })
      }]
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    } else {
      // 否则认为是就Requestbody
      config.headers['Content-Type'] = 'application/json;charset=utf-8'
      // get请求映射params参数
      if (config.method === 'get' && config.params) {
        let url = config.url + '?' + tansParams(config.params)
        url = url.slice(0, -1)
        config.params = {}
        config.url = url
      }
    }
    // Do something before request is sent
    if (!isNull(store.userStore.token)) {
      // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      if (!config.url.includes('/sso/oauth2/accessToken')) {
        config.headers.Authorization = store.userStore.token
      }
      config.headers.platform = 'pc'
    }

    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
     * 下面的注释为通过在response里，自定义code来标示请求状态
     * 当code返回如下情况则说明权限有问题，登出并返回到登录页
     * 如想通过 xmlhttprequest 来状态码标识 逻辑可写在下面error中
     * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
     */
  async response => {
    const res = response.data

    const code = res.code || 200
    const msg = errorCode[code] || res.msg || errorCode.default
    if (code === 401) {
      // prettier-ignore
      // 获取错误信息
      ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.userStore.logout().then(() => {
          // this.$router.push(`/login`)
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
    } else if (code === 500) {
      ElMessage({ message: msg, type: 'error' })
      return Promise.reject(new Error(msg))
    } else if (code === 601) {
      ElMessage({ message: msg, type: 'warning' })
      return Promise.reject(new Error(msg))
    } else if (code !== 200) {
      ElMessage({ message: msg, type: 'warning' })
      return Promise.reject(new Error('error'))
    } else {
      return Promise.resolve(response)
    }
  },
  (error) => {
    let { message } = error
    if (message === 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    ElMessage({ message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
)

export default service
